package com.erik.lin.collect;

import com.erik.lin.domain.DbInfo;
import lombok.SneakyThrows;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * Created by Erik on 2018/2/7.
 */
public class MysqlCollectAdapter extends CollectAdapter {

    public MysqlCollectAdapter(DbInfo dbInfo) {
        super(dbInfo);
        initializeMysqlProperties(dbInfo);
    }

    /** mysql采集模式名称获取 */
    private void initializeMysqlProperties(DbInfo dbInfo){
        String sourUrl = dbInfo.getParam().get("url");
        String schemaName = sourUrl.substring(sourUrl.lastIndexOf("/") + 1);
        if(schemaName.indexOf("?") > 0) {
            schemaName = schemaName.substring(0, schemaName.indexOf("?"));
        }
        dbInfo.getParam().put("tableSchema", schemaName);
    }

    @Override
    @SneakyThrows(IOException.class)
    public void initializeSqlSessionFactory(DbInfo dbInfo) {
        Configuration configuration = getConfiguration(dbInfo);
        Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath:collect/MysqlCollectMapper.xml");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(), configuration, resource.toString(), configuration.getSqlFragments());
        xmlMapperBuilder.parse();
        super.sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }
}